// 预算管理弹窗表单
<template>
  <div v-dialogDrag class="addDialog basic-from" :class="{previewPage: isReadonly}">
    <el-dialog custom-class="small-padding-dialog" :close-on-click-modal="false" :title="dialogTitle" :visible.sync="dialogVisible" width="1200px" @closed="handleClosed">
      <el-form ref="form" :rules="rules" :model="formData" class="form-wrap">
        <h4 class="full">预算信息</h4>
        <el-form-item label="物业名称" prop="choosedProperty" v-if="type == 'add'">
          <div>
            <el-button type="primary" class="add" size="mini" @click="$refs.chooseDialog2.show()" v-if="type == 'add'">选择物业</el-button>
            <choose-dialog ref="chooseDialog2" v-bind="chooseDialogAttrs2" @chooseData="handleChoose2" :disabledArr="choosedBillId" />
            <!--<el-input v-halfCharCode v-model="formData.propertyName" readonly placeholder="请输入物业名称" />-->
          </div>
          <el-row>
            <el-select v-model="choosedBillId" multiple placeholder="请选择">
              <el-option v-for="item in choosedProperty" :key="item.billId" :label="item.propertyName" :value="item.billId" />
            </el-select>
          </el-row>
        </el-form-item>
        <el-form-item label="物业名称" v-if="type != 'add'">
          <el-input v-halfCharCode v-model="formData.propertyName" readonly />
        </el-form-item>
        <el-form-item label="工程名称" prop="engineeringName">
          <el-input v-halfCharCode v-model="formData.engineeringName" maxlength="100" :readonly="isReadonly" placeholder="请输入工程名称" />
        </el-form-item>
        <h4 class="full">
          报价情况
          <el-button type="primary" size="mini" @click="addDepartment" v-if="!isReadonly" style="float:right;">添加</el-button>
        </h4>

        <el-table ref="multipleTable" :data="quoteInfoList" class="companyList full">
          <el-table-column label="单位名称" align="left">
            <template slot-scope="scope">
              <el-form-item v-if="!isReadonly">
                <el-input v-model="scope.row.unitName" readonly placeholder="请选择单位名称" maxlength="50">
                  <el-button slot="append" size="mini" v-if="!scope.row.readonly" @click="openUnitChoose(scope.$index)">选择</el-button>
                </el-input>
              </el-form-item>
              <span v-else>{{scope.row.unitName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位类型" width="200" align="left">
            <template slot-scope="scope">
              <el-form-item v-if="!scope.row.readonly">
                <el-select disabled placeholder="请选择单位类型" v-model="scope.row.unitType" v-if="companyDict.length">
                  <el-option :value="item.value.toString()" :label="item.label" :key="item.value" v-for="item in companyDict">{{item.label}}</el-option>
                </el-select>
              </el-form-item>
              <span v-else>{{getCompanyName(scope.row.unitType)}}</span>
            </template>
          </el-table-column>
          <el-table-column label="报价" width="200" align="left">
            <template slot-scope="scope">
              <el-form-item v-if="!scope.row.readonly">
                <el-input v-only-number="{min:0,precision:2}" v-model="scope.row.quotePrice" placeholder="请输入报价金额" maxlength="15" @input="handleQuotePriceChange($event, scope.$index)" />
              </el-form-item>
              <span v-else>{{scope.row.quotePrice | thousandMoney}}</span>
            </template>
          </el-table-column>
          <el-table-column label="中选" width="150" align="left">
            <template slot-scope="scope">
              <el-form-item v-if="!scope.row.readonly">
                <el-select clearable v-model="scope.row.isChoice" @change="handleChoiceChange($event, scope.$index)">
                  <el-option :value="item.value" v-for="item in choiceList" :key="item.value" :label="item.label" />
                </el-select>
              </el-form-item>
              <span v-else>{{scope.row.isChoice == '10' ?'中选':'不中选'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="130" v-if="!isReadonly" align="left">
            <template slot-scope="scope">
              <el-button type="text" size="mini" v-if="!scope.row.readonly" @click="removeItem(scope.$index)">移除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <h4 class="dialogItemTitle full">送审情况</h4>
        <el-form-item label="审核日期" prop="censorshipDate" class="dateChoose">
          <el-date-picker v-model="formData.censorshipDate" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="datetime" placeholder="请输入审核日期" :readonly="isReadonly" style="width:100%" :picker-options="pickerOptions" />
        </el-form-item>
        <el-form-item label="送审金额" prop="censorshipAmount">
          <el-input v-only-number="{min:0,precision:2}" maxlength="15" v-model="formData.censorshipAmount" :readonly="isReadonly" placeholder="请输入送审金额" v-if="!isReadonly" />
          <el-input :value="formData.censorshipAmount | thousandMoney" readonly v-else />
        </el-form-item>
        <el-form-item label="审定金额" prop="approvalAmount">
          <el-input v-only-number="{min:0,precision:2}" v-model="formData.approvalAmount" placeholder="请输入审定金额" maxlength="15" v-if="!isReadonly" />
          <el-input :value="formData.approvalAmount | thousandMoney" readonly v-else />
        </el-form-item>

        <el-form-item label="核减金额">
          <el-input :value="formData.reductionAmount | thousandMoney" disabled placeholder="请输入核减金额" />
        </el-form-item>

        <el-form-item label="核减率">
          <el-input v-model="formData.subtractRate" disabled placeholder="请输入核减率" />
        </el-form-item>
        <el-form-item label="审核公司" prop="auditCompany">
          <el-input v-halfCharCode v-model="formData.auditCompany" placeholder="请输入审核公司" :readonly="isReadonly" maxlength="15" />
        </el-form-item>
      </el-form>
      <!-- 物业选择弹窗 改用通用选择框了 -->
      <!--<propertyChooseDialog ref="propertyChoose" dialogType="budget" @changeProperty="handlePropertyChange" :disabledArr="choosedBillId" />-->
      <!-- 单位选择弹窗 -->
      <choose-dialog ref="chooseDialog" v-bind="chooseDialogAttrs" @chooseData="handleChoose" />
      <div slot="footer">
        <el-button @click="$bus.$emit('operationLog',formData.obtId)" v-if="type==='preview'">操作日志</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button v-if="type !== 'preview'" type="primary" v-throttle="[save]">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import propertyChooseDialog from "@/views/wy-operate/components/propertyChooseDialog";
import moment from 'moment'
import { calc } from '@/utils'
import {
  changeBudgetInfo,
  getQuoteList,
} from "@/views/wy-operate/api/repair";
export default {
  name: "addDepartment",
  components: {
    propertyChooseDialog,
  },
  inject: ['initList'],
  data () {
    return {
      type: "add", //弹窗类型，默认新增
      //弹窗开关
      dialogVisible: false,
      // 表单项
      formData: {
        operateName: "",
        billId: "",
        engineeringName: "",
        censorshipDate: "",
        censorshipAmount: "",
        approvalAmount: "",
        reductionAmount: "",
        subtractRate: "",
        auditCompany: "",
        roomId: '',
        propertyName: ''
      },

      choosedProperty: [],//实现多选效果用的
      choosedBillId: [],
      // 报价信息
      quoteInfoList: [],
      // 中选设置
      choiceList: [
        { label: "中选", value: "10" },
        { label: "不中选", value: "11" },
      ],
      // 单位选择弹窗
      openUnit: false,
      // 单位选择的当前行索引值
      editRowIndex: -1,

      pickerOptions: {
        disabledDate: function disabledDate (time) {
          //return time.getTime() < Date.now() // 选当前时间之后的时间
          return time.getTime() > Date.now() // 选当前时间之前的时间
        }
      },


    };
  },
  computed: {
    companyDict () {
      return this.getDict('provider_type')
    },
    // 弹窗标题计算
    dialogTitle () {
      return {
        preview: "查看",
        edit: "编辑",
        add: "新增",
      }[this.type];
    },
    // 是否只读
    isReadonly () {
      return this.type == "preview";
    },
    // 单位选择弹窗配置项
    chooseDialogAttrs () {
      return {
        title: "选择施工单位",
        placeholder: "请输入单位名称查询",
        url: `/api/clientprovider/page`,
        width: "1000px",
        searchKey: "clientProviderName",
        primaryKey: "supplierId",
        disabledArr: this.disabledUnitArr,
        showData: [
          {
            prop: "clientProviderName",
            label: "单位名称"
          },
          {
            prop: "clientProviderType",
            label: "单位类型",
            formatter: this.dataFormatter
          },
          { prop: "introduceUnit", label: "引进单位" },
          { prop: "telephone", label: "联系电话" },
        ]
      };

    },

    chooseDialogAttrs2 () {
      return {
        title: "修缮问题选择",
        placeholder: "请输入物业名称",
        url: `/api/repairbill/getproblem`,
        width: "1000px",
        searchKey: "propertyName",
        primaryKey: "billId",
        multiple: true,
        showData: [
          {
            label: "物业名称",
            prop: "propertyName"
          },
          {
            prop: "problemDesc",
            label: "问题描述"
          },
          {
            prop: "initiateTime",
            label: "上报时间",
            formatter: this.dataFormatter
          },
          {
            prop: "initiator",
            label: "上报人"
          }

        ],
        reserveSelection: true

      };
    },
    // 单位弹窗禁选项
    disabledUnitArr () {
      return this.quoteInfoList.map(i => i.supplierId)
    },
    // 校验规则
    rules () {
      return {
        propertyName: [{ required: true, message: '物业名称不能为空', trigger: 'blur' }],
        engineeringName: [{ required: true, message: '工程名称不能为空', trigger: 'blur' },
        { min: 1, max: 25, message: '长度在 1 到 25 个字符', trigger: 'blur' }],
        // 送审
        censorshipAmount: [
          { pattern: /(^(([1-9]+\d*)|(0{1}))(.\d{1,2})?)|(^-([1-9]+\d*(\.\d{1,2})?|0\.(0[1-9]{1}|[1-9]{1}\d?)))/, message: "请输入正确的金额", trigger: "blur" },
          { validator: this.validateCensorshipAmount, trigger: "blur" },
        ],
        // 审定
        approvalAmount: [
          { pattern: /(^(([1-9]+\d*)|(0{1}))(.\d{1,2})?)|(^-([1-9]+\d*(\.\d{1,2})?|0\.(0[1-9]{1}|[1-9]{1}\d?)))/, message: "请输入正确的金额", trigger: "blur" },
          { validator: this.validateApprovalAmount, trigger: "blur" },
        ],
      }
    },
  },
  watch: {
    //送审金额
    'formData.censorshipAmount': function (val) {
      //核减金额
      let reductionAmount = calc.Sub(Number(val), Number(this.formData.approvalAmount))
      this.formData.reductionAmount = reductionAmount || 0
      // 核减率
      let subtractRate = calc.Div(Number(reductionAmount), Number(val))
      this.formData.subtractRate = subtractRate ? (subtractRate * 100).toFixed(2) + '%' : '0%'
    },
    //审定金额
    'formData.approvalAmount': function (val) {
      //核减金额
      let reductionAmount = calc.Sub(Number(this.formData.censorshipAmount), Number(val))
      this.formData.reductionAmount = reductionAmount || 0
      // 核减率
      let subtractRate = calc.Div(Number(reductionAmount), Number(this.formData.censorshipAmount))
      this.formData.subtractRate = subtractRate ? (subtractRate * 100).toFixed(2) + '%' : '0%'
    },

    'choosedBillId': {
      deep: true,
      handler (val) {
        this.formData.billId = val;//val.join(",");

        this.choosedProperty = this.choosedProperty.filter(i => val.includes(i.billId));

        //alert(JSON.stringify(this.choosedProperty))
        let propertyNames = this.choosedProperty.reduce(
          (total, item) =>
            total ? `${total},${item.propertyName}` : item.propertyName, ""
        );
        this.formData.propertyName = propertyNames;

        let roomIds = this.choosedProperty.reduce(
          (total, item) =>
            total ? `${total},${item.roomId}` : item.roomId, ""
        );
        this.formData.roomId = roomIds;
        //工程名称
        if (this.choosedProperty.length > 1) {
          this.formData.engineeringName = this.choosedProperty[0].propertyName + "等维护工程"
        }
        else if (this.choosedProperty.length > 0) {
          this.formData.engineeringName = this.choosedProperty[0].propertyName + "维护工程";
        }
      }
    },
    dialogVisible (val) {
      if (!val) {
        this.choosedProperty = [];
        this.choosedBillId = [];
      }
    }
  },
  methods: {
    // 校验送审金额
    validateCensorshipAmount (rule, value, callback) {
      if (this.formData.approvalAmount != '' && value == '') {
        return callback(new Error('送审金额不能为空!'))
      }
      callback()
    },
    // 校验审定金额
    validateApprovalAmount (rule, value, callback) {
      // 送审金额填了，审定金额也要填；
      if (this.formData.censorshipAmount != '' && value == '') {
        callback(new Error('审定金额不能为空!'))
        return;
      }
      //审定金额不能高于送审金额
      if (Number(this.formData.censorshipAmount) < Number(value)) {
        callback(new Error('审定金额不能高于送审金额'))
        return;
      }
      callback()
    },
    //开启弹窗
    async show ({ type, data = {} }) {
      this.dialogVisible = true;
      this.type = type;
      if (["preview", "edit"].includes(type)) {
        const result = await this.http(`/api/operationbudget/${data.obtId}`)
        this.formData = result.data.data;
        // 获取报价列表
        const res = await getQuoteList(data.obtId);
        // 判断没有报价的情况
        if (res.data.data.length && res.data.data[0].quoteInfo) {
          this.quoteInfoList = res.data.data.map((item) => {
            return {
              ...item.quoteInfo,
              readonly: true,
            };
          });
        }
      }
    },
    // 提交新增
    save () {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return false;
        if (this.quoteInfoListVerify()) {
          let params = {
            billId: this.formData.billId,
            operationBudget: this.formData,
            quoteInfoList: this.quoteInfoList,
          };
          params.operationBudget.reductionAmount = parseFloat(params.operationBudget.reductionAmount)
          changeBudgetInfo(params, this.type).then(res => {
            if (res.data.data.code == 200) {
              this.$message.success(`${this.dialogTitle}成功!`);
              this.dialogVisible = false
              this.initList({ current: 1, keyword: '' })
            } else {
              this.$message.error(res.data.msg || res.data.data.msg)
            }
          })
        }
      });
    },
    // 报价情况校验{ pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的金额", trigger: "blur" },
    quoteInfoListVerify () {
      if (!this.quoteInfoList.length) {
        this.$message.error('报价情况不能为空')
        return false
      } else if (this.quoteInfoList.some(item => item.quotePrice == undefined || item.quotePrice == '')) {
        this.$message.error('报价金额不能为空')
        return false
      } else if (this.quoteInfoList.some(item => !/^\d+(\.\d{1,2})?$/.test(item.quotePrice))) {
        this.$message.error('请填写正确报价金额')
        return false
      } else if (this.quoteInfoList.filter(i => i.isChoice == '10').length > 1) {
        this.$message.error('中选单位最多只能有一个')
        return false
      } else {
        return true
      }
    },
    // 监听物业改变
    /*
    handlePropertyChange (data) {
      //console.log(data)
      this.formData = {
        ...this.formData,
        propertyName: data.propertyName,
        engineeringName: data.propertyName + '维护工程',
        billId: data.billId,
        roomId: data.roomId
      }
      this.$refs.form.resetFields()
    },
    */
    // 新增单位
    addDepartment () {
      this.quoteInfoList.push({
        supplierId: "",
        clientProviderName: "",
        clientProviderType: "",
        isChoice: "11", //10中选，11不中选
      });
    },
    // 移除报价
    removeItem (index) {
      if (this.quoteInfoList[index].isChoice === '10') {
        this.formData.approvalAmount = this.formData.censorshipAmount = ''
      }
      this.quoteInfoList.splice(index, 1)
    },
    // 监听选中修改
    handleChoiceChange (value, index) {
      if (value == '10') {
        // 修改列表其他单位的中选状态
        this.quoteInfoList = this.quoteInfoList.map((item, i) => {
          if (index != i) {
            item.isChoice = "11";
          }
          return item
        })
      }
      // 修改送审、审定金额
      let quotePrice = this.quoteInfoList[index].quotePrice
      let judge = value === '10' && quotePrice && Number(quotePrice) > 50000
      this.formData.approvalAmount = this.formData.censorshipAmount = judge ? quotePrice : ''
    },
    // 监听报价修改
    handleQuotePriceChange (val, index) {
      if (this.quoteInfoList[index].isChoice === '10') {
        this.formData.approvalAmount = this.formData.censorshipAmount = val && Number(val) > 50000 ? val : ''
      }
    },
    // 弹窗关闭回调
    handleClosed () {
      this.$refs.form.resetFields();
      this.quoteInfoList = [];
    },
    // 开启单位选择弹窗
    openUnitChoose (index) {
      this.editRowIndex = index
      this.$refs.chooseDialog.show()

    },
    // 获取公司单位类型
    getCompanyName (unitType) {
      let companyType = this.companyDict.find(item => item.value == unitType)
      return companyType ? companyType.label : ''
    },
    // 单位选择弹窗选中事件
    handleChoose ({ supplierId, clientProviderName, clientProviderType }) {
      this.quoteInfoList = this.quoteInfoList.map((item, index) => {
        if (index === this.editRowIndex) {
          return { ...item, supplierId, unitName: clientProviderName, quoteId: supplierId, unitType: clientProviderType }
        }
        return item
      })
    },

    //工单选择
    handleChoose2 (data) {
      //this.put(data);
      this.choosedProperty = [...this.choosedProperty, ...data];
      this.choosedBillId = this.choosedProperty.map(i => i.billId);

      callback && callback();
    },

    //将选择工单放到表单中
    //put(selectedData, callback){
    //
    //},

    // 单位选择弹窗数据格式化
    dataFormatter (row, column, cellValue) {
      switch (column.property) {
        case 'clientProviderType':
          return this.getCompanyName(cellValue)
        case 'initiateTime':
          return moment(cellValue).format('YYYY-MM-DD')
        default:
          return cellValue
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
.por {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.dateChoose {
  /deep/ .el-form-item__label {
    float: none;
  }
}
.companyList .el-form-item {
  margin-bottom: 0;
}
.el-input-group__append button.el-button {
  color: #fff;
  background-color: #2f54eb;
  border-color: #2f54eb;
}
</style>
